package lixp.jwt.utils.Imp;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lixp.err.MyException;
import lixp.jwt.utils.IJwtUtils;
import lixp.res.ResultEnum;
import lixp.res.ResultUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static java.lang.System.out;

@Data
@ConfigurationProperties(prefix = "config.jwt")
@Component
public class JwtUtilForJJwt implements IJwtUtils {

    /**
     *  加密的秘钥
     */
    private String secret;
    /**
     *  过期时间
     */
    private long expire;
    private String header;

    @Override
    public String creatToken(Integer userId) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        out.println(secret);

        //生成token的头部信息
        Map<String, Object> headerMap = new HashMap<String, Object>();
        headerMap.put("alg", "HS256");
        headerMap.put("typ", "JWT");

        //生成token，包含头部信息、载荷和算法签名
        return Jwts.builder()
                .setHeaderParams(headerMap)
                .setAudience(userId.toString())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();

    }



    @Override
    public Integer getUserIdFromToken(String token) throws MyException {
        Claims claims;
        try{
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            throw new MyException(ResultUtil.error(ResultEnum.Token_ERROR));

        }

        String audience = claims.getAudience();
        return Integer.parseInt(audience);
    }
}
